﻿using System;
using Pomelo.UnityWebSocketPomelo;
using SimpleJson;
using UnityEngine;

namespace TEngine
{
    /// <summary>
    /// 网络模块。
    /// </summary>
    [DisallowMultipleComponent]
    public sealed partial class NetworkModule : Module
    {
        private UnityWebSocketPomeloClient pClient;

        /// <summary>
        /// 游戏框架组件初始化。
        /// </summary>
        protected override void Awake()
        {
            base.Awake();

            pClient = new UnityWebSocketPomeloClient(this);
            // _timerManager = ModuleImpSystem.GetModule<TimerManager>();
            // if (_timerManager == null)
            // {
            //     Log.Fatal("TimerMgr is invalid.");
            // }
        }

        // public UnityWebSocketPomeloClient PomeloClient()
        // {
        //     return pClient;
        // }

        public void initClient(string address, Action callback = null)
        {
            pClient.initClient(address, callback);
        }

        public void Send(string route, JsonObject msg, Action<JsonObject> callFunc = null)
        {
            if (callFunc != null)
            {
                pClient.request(route, msg, callFunc);
            }
            else
            {
                pClient.notify(route, msg);
            }
        }

        public void On(string eventName, Action<JsonObject> action)
        {
            pClient.on(eventName, action);
        }

        public void Off(string eventName)
        {
            pClient.off(eventName);
        }

        public void Disconnect()
        {
            pClient.disconnect();
            pClient = null;
            pClient = new UnityWebSocketPomeloClient(this);
        }
        
    }
}